package soulkun.library.component

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes

abstract class BaseDialog : Dialog{

    companion object{
        var TAG = "BaseDialog"
    }
    protected var decorView: ViewGroup? = null

    constructor(context: Context, @LayoutRes resId: Int): this(context, resId, 0)

    constructor(context: Context, @LayoutRes resId: Int, themeResId: Int): super(context, themeResId){
        TAG = "TAG:" + javaClass.simpleName
        setContentView(resId)
        window!!.setBackgroundDrawable(ColorDrawable(0))
        window!!.setDimAmount(0.5f)
        decorView = window!!.decorView as ViewGroup
    }

    open fun setViewOnClickListener(@IdRes resID: Int, listener: View.OnClickListener?) {
        findViewById<View>(resID).setOnClickListener(listener)
    }

    open fun findTextView(@IdRes resID: Int): TextView? {
        return findViewById(resID)
    }

    open fun findImageView(@IdRes resID: Int): ImageView? {
        return findViewById(resID)
    }

    open fun findButtonView(@IdRes resID: Int): Button? {
        return findViewById(resID)
    }

    class Builder(private val context: Context) {

        private var layoutId = 0
        private val viewIdArrayList = ArrayList<Int>()
        private val clickListenerArrayList = ArrayList<View.OnClickListener>()

        fun setLayout(@LayoutRes layoutId: Int): Builder {
            this.layoutId = layoutId
            return this
        }

        fun addViewOnClickListener(@IdRes resID: Int, listener: View.OnClickListener): Builder{
            this.viewIdArrayList.add(resID)
            this.clickListenerArrayList.add(listener)
            return this
        }

        fun builder(): BaseDialog {
            if (layoutId == 0) {
                throw NullPointerException("Dialog is missing layout file")
            }
            val dialog: BaseDialog = object : BaseDialog(context, layoutId) {}
            for (index in 0 until viewIdArrayList.size) {
                dialog.setViewOnClickListener(viewIdArrayList[index], clickListenerArrayList[index])
            }
            return dialog
        }

    }

}